#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>

void helper_array_create_list(char **indata, size_t *insizes, int items, char **data, size_t *size) {
	uint32_t i, items_u32;
	char *ptr;

	/*
	 * Base size of an array: uint32_t for number of items, n*size_t for size information.
	 * Each item also has its size.
	 */
	(*size) = sizeof(uint32_t) + items*sizeof(size_t);
	items_u32 = (uint32_t)items;
	for (i = 0; i < items_u32; i++) {
		(*size) += insizes[i];
	}

	/*
	 * Allocate data and start copying.
	 */
	(*data) = malloc(*size);

	/* Number of items in the array. */
	memcpy(*data, &items_u32, sizeof(items_u32));

	/* Copy data. */
	ptr = *data;
	ptr += sizeof(items_u32);
	for (i = 0; i < items_u32; i++) {
		memcpy(ptr, &insizes[i], sizeof(insizes[i]));
		ptr += sizeof(insizes[i]);
		memcpy(ptr, indata[i], insizes[i]);
		ptr += insizes[i];
	}
}

int helper_array_get_item(char *indata, size_t insize, int item, char **data, size_t *size) {
	char *ptr;
	uint32_t i, items_u32, request_u32;
	size_t item_size;

	items_u32 = *(uint32_t*)indata;
	request_u32 = (uint32_t)item;

	/* Array out of bounds. */
	if (request_u32 >= items_u32)
		return -1;
	
	ptr = indata;
	ptr += sizeof(items_u32);
	for (i = 0; i < request_u32; i++) {
		item_size = *(size_t*)ptr;
		ptr += sizeof(item_size) + item_size;
	}

	(*data) = ptr;
	(*size) = *(size_t*)ptr;
	return 0;
}
